var isFirstLoad = true;
var scrollTop;
var divTop;
var hasViewedInvo = false;
var INDEX_EINV = 0;
var INDEX_PAPER = 1;
function setScrollTop(){
	scrollTop=$(".step_offset").offset().top;
	divTop=$(window).scrollTop()+$(window).height()-62;
	if(divTop<scrollTop){
		$("#orderTotal").addClass("orderTotalFixed").removeClass("orderTotal");

	}else{
	  	$("#orderTotal").removeClass("orderTotalFixed").addClass("orderTotal");
	}
}
//验证码
function captchaImage(){
	jQuery("#captchaImage").attr("src", "http://public.jiuxian.com/public/captchaimg.htm?timestamp" + (new Date()).valueOf());
}
function captchaImage2(){
	jQuery("#captchaImage2").attr("src", "http://public.jiuxian.com/public/captchaimg.htm?timestamp" + (new Date()).valueOf());
}
//保留2位小数点
function returnFloat2(value) {
    return value.toFixed(2);
}
//验证支付密码
function checkPassword(){
	var payPassword = jQuery.trim($("#inv_payee").val());
	if(payPassword == ""){
		$("#alertstyle7").html("请填写支付密码!");
		$("#inv_payee").focus();
		return false;
	}
	jQuery.ajax({
		 type:'post',
		 url:'/order/checkPayPassword.htm',
		 data:{'payPassword':payPassword},
		 dataType:'json',
		 cache:false,
		 async:false,
		 success:function(data){
			 if(data == null || data.message == null || data.message == "" || data.message == "ERROR"){
				 alert("操作失败,请稍后重试!!!");
				 return false;
			 }else{
				 if(data.message == "SUCCESS"){
					 $("#inv_payee").attr("disabled", true);
					 $("#alertstyle7").html("");
					 $("#paypass").val("1");
					 $("#useBtn2").hide();
					 $("#successstyle").html("密码正确!");
					 changePayPrice();
					 return true;
				 }else if(data.message == "PASSWORD_EMPTY"){
					 $("#alertstyle7").html("请先设置支付密码!");
					 return false;
				 }else if(data.message == "PASSWORD_ERROR"){
					 $("#alertstyle7").html("支付密码错误!");
					 return false;
				 }else if(data.message == "PASSWORD_ERROR_MAX_COUNT"){
					 $("#alertstyle7").html("支付密码1小时内错误5次,已锁定.请去用户中心重置!");
					 return false;
				 }
			 }
		 },
		 error:function(){
			 alert("操作失败,请稍后重试!!!");
			 return false;
		 }
	 });
}

//获取用户红包
function searchCoupon(){
	jQuery.ajax({
		 type:'post',
		 url:'/order/searchCoupon.htm',
		 dataType:'json',
		 cache:false,
		 async:true,
		 success:function(data){
	 		$("#useCouponList").empty();
	 		$("#notUseCouponList").empty();
	 		$("#useCouponList").append("<a class='open' href='javascript:;' id='azk'>展开<i></i></a>");
	 		$("#notUseCouponList").append("<a class='open' href='javascript:;' id='azk2'>展开<i></i></a>");
	 		var canUseNum = 0;
	 		var notCanUseNum = 0;
	 		if(data != null && data.list != null && data.list.length > 0){
				for(var i = 0;i<data.list.length;i++){
					if(data.list[i].isCanUse == 1){
						canUseNum++;
						var checkTmp = "";
						if(canUseNum==1){
							checkTmp="checked='checked'";
						}
						$("#useCouponList").append("<span><input type='radio' value='"+data.list[i].ID+"' class='bonus' "+checkTmp+" name='bonus' _di='"+data.list[i].price+"'/><em class='ggname'>"+data.list[i].Name+"[￥"+data.list[i].price+".00]</em><em>有效期至"+data.list[i].BlankOutTime+"</em></span>");
					}else{
						notCanUseNum++;
						$("#notUseCouponList").append("<span><input type='radio' value='"+data.list[i].ID+"' name='notbonus' disabled='disabled' _di='"+data.list[i].price+"'/><em class='ggname'>"+data.list[i].Name+"[￥"+data.list[i].price+".00]</em><em>有效期至"+data.list[i].BlankOutTime+"</em></span>");
					}
				}
	 		}
			if(canUseNum<=4){$("#azk").hide();$("#useCouponList").css("height","auto");}
			if(canUseNum==0){
				$("#useCouponList").parent().find('.giftCardTit,.giftCard').hide();
		 		$("#useCouponList").append("<span><input type='radio' value='0' _di='0' class='bonus' checked='checked' name='bonus'/><em class='ggname'>不使用礼券</em></span>");
				$(".giftCardW span").text("此单暂无可用的优惠券");
			}else{
		 		$("#useCouponList").append("<span><input type='radio' value='0' _di='0' class='bonus' name='bonus'/><em class='ggname'>不使用礼券</em></span>");
				$(".giftCardW span").text("以下是此订单可用的优惠券");
				$("#useCouponList").parent().find('.giftCardTit,.giftCard').show();
				if($('#youhunjuan').css('display')=='none'){
					$("#hongbao").click();
				}
			}
			if(notCanUseNum==0){
				$("#notCanUseNum").parent().hide();
			}else{
				if(notCanUseNum<=5){$("#azk2").hide();$("#notUseCouponList").css("height","auto");}
				$("#notCanUseNum").parent().show();
			}
			changePayPrice();
			$("#canUseNumInput").val(canUseNum);
			$("#notCanUseNumInput").val(canUseNum);
			$("#canUseNum").html("("+canUseNum+")");
			$("#notCanUseNum").html("("+notCanUseNum+")");
			if(checkedCouponValue != null && checkedCouponValue !=undefined && checkedCouponValue !=""){
				$("input[name='bonus'][value='"+checkedCouponValue+"']").attr("checked",'checked');
			}
			$("#couponTr").show();
			setScrollTop();
		 },
		 error:function(){
			 //alert("操作失败,请稍后重试!!!");
		 }
	 });
}

var checkedCouponValue = "";

//计算金额
function changePayPrice(){
	//是否使用红包
	var isCoupon = false;
	var couponPrice= "0";
	try{
		couponPrice = $('input:radio[name="bonus"]:checked').attr('_di');
		checkedCouponValue = $('input:radio[name="bonus"]:checked').val();
	}catch (e) {
	}
	if(couponPrice != undefined && couponPrice != null && couponPrice != "0"){
		isCoupon = true;
	}
	//是否使用余额
	var isAccout = false;
	var accoutPrice = $("#accoutMoneyInput").val();
	if(accoutPrice != undefined && accoutPrice != "" && accoutPrice>0){
		isAccout = true;
	}
	//是否使用返现
	var isBack = false;
	var backPrice = $("#cashbackInput").val();
	if(backPrice != undefined && backPrice != "" && backPrice>0){
		isBack = true;
	}
	
	var giftCardPrice = 0;
	$("[name='giftCards']").each(function(){
		 if($(this).attr("checked")){
			 if($(this).attr('_di') != undefined){
				 giftCardPrice = parseFloat(giftCardPrice) + parseFloat($(this).attr('_di'));
			 }
		 }
	});
	//计算总额  红包>牛币>返现>礼品卡>余额
	var totalPrice = $("#totalPrice").val();
	$("#productcount").html($("#procount").val());
	var productPrice = $("#productPrice").val();
	$("#zje_i").html("￥"+productPrice);
	$("#jbcount").html($("#pointsCount").val());
	var priceCutAmount = $("#priceCutAmount").val();
	if(priceCutAmount != "" && priceCutAmount > 0){
		$("#yh_i").html("-￥"+priceCutAmount);
		$("#yh_div").show();
	}
	var forcxyh = $("#forcxyh").html();
	if(forcxyh != null && forcxyh != ""){
		$("#cxyhdetail").html(forcxyh);
		$("#cxyh").show();
	}
	var payPrice = totalPrice;
	var useCouponPrice = 0;
	var useBackPrice = 0;
	//红包
	if(isCoupon){
		var canUseBonusPrice = $("#canUseBonusPrice").val();
		if(canUseBonusPrice != undefined && canUseBonusPrice != "" && canUseBonusPrice != null && canUseBonusPrice > 0 && parseFloat(canUseBonusPrice) <= parseFloat(couponPrice)){
			couponPrice = canUseBonusPrice;
		}
		payPrice = parseFloat(payPrice) - parseFloat(couponPrice);
		useCouponPrice = parseFloat(couponPrice);
		$("#yhq_i").html("-￥" + parseFloat(couponPrice).toFixed(2));
		$("#yhq_div").show();
	} else {
		$("#yhq_div").hide();
	}
	if(payPrice<0){
		payPrice = 0;
	}
	//返现
	if(isBack && parseFloat(backPrice) > 0){
		payPrice = parseFloat(payPrice) - parseFloat(backPrice);
		useBackPrice = parseFloat(backPrice);
		$("#fx_i").html("-￥" + parseFloat(backPrice).toFixed(2));
		$("#fx_div").show();
	} else {
		$("#fx_div").hide();
	}
	if(payPrice<0){
		$("#cashbackInput").val(parseFloat((parseFloat(backPrice)-parseFloat(payPrice)*parseFloat(-1)).toFixed(2)));
		$("#fx_i").html("-￥" + parseFloat((parseFloat(backPrice)-parseFloat(payPrice)*parseFloat(-1)).toFixed(2)));
		$("#fx_div").show();
		useBackPrice = parseFloat(parseFloat(backPrice)-parseFloat(payPrice)*parseFloat(-1));
		payPrice = 0;
	}
	if(priceCutAmount != null && priceCutAmount != ""){
		productPrice = parseFloat(productPrice) - parseFloat(priceCutAmount);
	}
	productPrice = parseFloat(productPrice) - parseFloat(useCouponPrice) - parseFloat(useBackPrice);
	var expensesPrice = 0;
	var carriageFree = $("#carriageFree").val();
	var addressId = $(".addressList .on input").val();
	jQuery.ajax({
		 type:'post',
		 url:'/order/getExpensesPrice.htm',
		 data:{'addressId':addressId,'totalPrice':productPrice,'carriageFree':carriageFree},
		 dataType:'json',
		 cache:false,
		 async:false,
		 success:function(data){
			if(data.expensesPrice != null){
				var isAllExchangeGoods = $("#isAllExchangeGoods").val();
				if(isAllExchangeGoods !=undefined && isAllExchangeGoods=="true"){
					expensesPrice = returnFloat2(parseFloat($("#expensesPrice").val()));
				}else{
					expensesPrice = returnFloat2(data.expensesPrice);
					if(parseInt(expensesPrice) > 0){
						var hasExchangeGoods = $("#hasExchangeGoods").val(); 
						if(hasExchangeGoods !=undefined && hasExchangeGoods=="true"){
							expensesPrice = returnFloat2(parseFloat($("#exchangeGoodsExpensesPrice").val()));
						}
					}
				}
				$("#yf_i").html("￥"+expensesPrice);
				$("#yf_div").show();
				payPrice = parseFloat(payPrice) + parseFloat(expensesPrice);
				//礼品卡
				if(payPrice > 0){
					if(parseFloat(giftCardPrice) > 0){
						if(parseFloat(payPrice) > parseFloat(giftCardPrice)) {
							$("#lpk_i").html("-￥" + parseFloat(giftCardPrice).toFixed(2));
							$("#lpk_div").show();
						} else {
							$("#lpk_i").html("-￥" + parseFloat(payPrice).toFixed(2));
							$("#lpk_div").show();
						}
					}
					payPrice = parseFloat(payPrice) - parseFloat(giftCardPrice);
					//礼品卡已消费,修改礼品卡使用多少,剩余多少
					if(payPrice>=0){
						$("[name='giftCards']").each(function(){
							 if($(this).attr("checked")){
								 if($(this).attr('_di') != undefined){
									 var id = $(this).attr("id");
									 $("#"+id+"_SHIYONG").text(returnFloat2(parseFloat($(this).attr('_di')))+"元");
								 }
							 }
						});
					}else{	//有剩余金额,修改礼品卡使用多少,剩余多少
						//剩余金额
						var surplus = parseFloat(payPrice)*parseFloat(-1);
						var use = 0;
						$("[name='giftCards']").each(function(){
							 if($(this).attr("checked")){
								 if($(this).attr('_di') != undefined){
									 var id = $(this).attr("id");
									 use = parseFloat(use) + parseFloat($(this).attr('_di'));
									 //最后一张卡
									 if(parseFloat(use) == parseFloat(giftCardPrice)){
										 $("#"+id+"_SHIYONG").text(returnFloat2(parseFloat($(this).attr('_di'))-parseFloat(surplus))+"元");
										 $("#"+id+"_SHENGYU").text(returnFloat2(surplus)+"元");
									 }else{
										 $("#"+id+"_SHIYONG").text(returnFloat2(parseFloat($(this).attr('_di')))+"元");
										 $("#"+id+"_SHENGYU").text("0.00元");
									 }
								 }
							 }
						});
					}
					if(payPrice<0){
						payPrice = 0;
					}
				}else{
					if(giftCardPrice > 0){
						$("#lpk_div").hide();
						$("#alertstyle6").html("当前账单支付金额为0.00,无需使用礼品卡支付!");
					}
					$("input[type='checkbox'][name='giftCards']").removeAttr("checked");
				}
				checkGiftCartErrorPrice();
				//余额
				if(payPrice>0){//余额开发票
					$("#fapiaoxinxi").removeAttr("disabled");
				}
				if(isAccout && parseFloat(accoutPrice) > 0){
					payPrice = parseFloat(payPrice) - parseFloat(accoutPrice);
					$("#ye_i").html("-￥" + parseFloat(accoutPrice).toFixed(2));
					$("#ye_div").show();
				} else {
					$("#ye_div").hide();
				}
				if(payPrice<0){
					if(parseFloat(accoutPrice)-parseFloat(payPrice)*parseFloat(-1) >= 0){
						$("#accoutMoneyInput").val(parseFloat((parseFloat(accoutPrice)-parseFloat(payPrice)*parseFloat(-1)).toFixed(2)));
						$("#ye_i").html("-￥" + parseFloat((parseFloat(accoutPrice)-parseFloat(payPrice)*parseFloat(-1)).toFixed(2)));
						$("#ye_div").show();
					}else{
						$("#accoutMoneyInput").val(0);
						$("#ye_div").hide();
					}
					payPrice = 0;
				}
				$("#toPayPrice").val(returnFloat2(parseFloat(payPrice)));
				$("#payPrice").html("￥"+returnFloat2(parseFloat(payPrice)));
			}
		 },
		 error:function(){
			 alert("操作失败,请稍后重试!!!");
			 return false;
		 }
	 });
	
}
//检查礼品卡错误金额
function checkGiftCartErrorPrice(){
	$("[name='giftCards']").each(function(){
		 if($(this).attr("checked")){
			 if($(this).attr('_di') != undefined){
				 var id = $(this).attr("id");
				 var price = $("#"+id+"_SHIYONG").text().replace("元","");
				 if(parseFloat(price)<0){
					 $(this).removeAttr("checked");
					 $("#"+id+"_SHIYONG").text("0.00元");
					 $("#"+id+"_SHENGYU").text("0.00元");
					 changePayPrice();
				 }
			 }
		 }
	});
}
//验证表单
function refreshFormData(){
	if($(".subBtn").attr("a") == "a"){	//处理中
		return;
	}
	$(".subBtn").css("background","#939393");
	$(".subBtn").attr("a","a");
	var form =  document._orderform;
	// 检验1元购验证码
	
	var hasZnqxgGoods = $("#hasZnqxgGoods").val();
	if(hasZnqxgGoods != undefined && hasZnqxgGoods == 'true'){
		var znqVerificationCode = $("#znqVerificationCode").val();
		var reg = /^[0-9a-zA-Z]+$/;
		if(znqVerificationCode == undefined || $.trim(znqVerificationCode) == ''){
			$(".popMask").show();
			$(".popBox").show();
			jQuery("#captchaImage2").attr("src", "http://public.jiuxian.com/public/captchaimg.htm?timestamp" + (new Date()).valueOf());
			removeDisabledButton();
			return false;
		}else if($.trim(znqVerificationCode).length != 4){
			$(".popMask").show();
			$(".popBox").show();
			jQuery("#captchaImage2").attr("src", "http://public.jiuxian.com/public/captchaimg.htm?timestamp" + (new Date()).valueOf());
			removeDisabledButton();
			return false;
		}else if(!reg.test($.trim(znqVerificationCode))){
			$(".popMask").show();
			$(".popBox").show();
			jQuery("#captchaImage2").attr("src", "http://public.jiuxian.com/public/captchaimg.htm?timestamp" + (new Date()).valueOf());
			removeDisabledButton();
			return false;
		}else{
			form.znqVerificationCode.value = znqVerificationCode;
		}
	}
	
	//是否使用余额
	var accoutPrice = $("#accoutMoneyInput").val();
	var backPrice = $("#cashbackInput").val();
	var inv_payee = $("#inv_payee").val();
	if((accoutPrice != undefined && accoutPrice != "" && accoutPrice>0) || (backPrice != undefined && backPrice != "" && backPrice>0)){
		if($("#paypass").val() != "1" || inv_payee == ""){
			if(inv_payee == ""){
				$("#alertstyle7").html("请填写支付密码!");
				$("#inv_payee").focus();
				removeDisabledButton();
				return false;
			}else{
//				$("#alertstyle7").html("请点击确认密码来验证!");
//				$("#inv_payee").focus();
				;
			}
			if(checkPassword()){
			}else{
				removeDisabledButton();
				return false;
			}
		}
	}
	if(inv_payee == null || inv_payee == undefined || inv_payee == ""){
		form.payPassWord.value = "";
	}else{
		form.payPassWord.value = inv_payee;
	}
	//帐户余额
	if(accoutPrice != undefined && accoutPrice != "" && accoutPrice>=0){
		form.useAccoutMoney.value = accoutPrice;
	}
	//返现
	if(backPrice != undefined && backPrice != "" && backPrice>=0){
		form.useCashback.value = backPrice;
	}
	//收货地址(获取ID具体详细去地址表取)
	var addressitem = $(".addressList .on input").val();
	if(addressitem == null || addressitem == undefined || addressitem == "" || addressitem <= 0){
		$(".submit-pro").html("<span>请选择用户地址!</span>").show();
		removeDisabledButton();
		return false;
	}
	var addressname = $(".addressList .on input").attr("addressname");
	if(addressname != null && addressname != undefined){
		if(addressname.split("-")[0] == "香港" || addressname.split("-")[0] == "澳门" || addressname.split("-")[0] == "台湾"){
			$(".submit-pro").html("<span>您所选的区域暂停配送!</span>").show();
			removeDisabledButton();
			return false;
		}
	}
	form.addressId.value = addressitem;
	
	//支付方式
	var sel_pay = $('input:radio[name="sel_pay"]:checked').val();
	if(sel_pay == "1"){
		form.paymentChannelName.value=encodeURI("货到付款");
		form.paymentChannel.value = "100";
	}else if(sel_pay == "3"){
		form.paymentChannelName.value=encodeURI("线下汇款");
		form.paymentChannel.value = "131";
	}else if(sel_pay == "2"){		
		var payWayID = $("#payid").val();
		if(payWayID == 100 || payWayID == 103 || payWayID == 131 || payWayID == 146){
			payWayID = 101;
		}
		form.paymentChannel.value = payWayID;
	}else if(sel_pay == "4"){
		form.paymentChannelName.value=encodeURI("支付宝货到付款");
		form.paymentChannel.value = "146";
	}else{
		$(".submit-pro").html("<span>请选择支付方式!</span>").show();
		removeDisabledButton();
		return false;
	}
	//礼品卡
	var giftCards = "";
	$("[name='giftCards']").each(function(){
		 if($(this).attr("checked")){
			 if($(this).attr('_di') != undefined){
				 giftCards += "," + $(this).val();
			 }
		 }
	});
	if(giftCards != null){
		form.useGiftCards.value = giftCards;
	}
	//红包
	var bonus = 0;
	try{
		bonus = $(":radio[name='bonus']:checked").val();
		if(bonus == null || bonus == undefined || bonus == "" || bonus == "0"){
			bonus = 0;
		}
	}catch (e) {
		bonus = 0;
	}
	form.useCoupon.value = bonus;

	//发票
	//form.invoiceType.value = $(":radio[name='InvoiceCustom'][checked]").val();去掉此选项
	var invTitle = $("#invoiceTitCon").val();
	if($("#fapiaoxinxi").attr('checked')=="checked"){
		if(invTitle == "个人" || invTitle == ""){
			form.invoiceType.value = 1;
			form.invoiceTitle.value = encodeURI("个人");
		}else{
			form.invoiceType.value = 2;
			form.invoiceTitle.value = encodeURI(invTitle);
		}
	}
	form.invoiceContent.value = encodeURI($(":radio[name=inv_con][checked]").attr('title'));
	//发票材质(1电子2纸质)
	form.invoiceKinds.value = $("input[name=inv_type]:checked").val();
	if(form.invoiceKinds.value=="1"){
		form.invoiceMobile.value = getRealPhone($("#inv_mobile").val());
	}
	//酒水随附单
	//form.needAttachedSheet.value = $(":checkbox[name='attached_sheet']").attr("checked")=="checked"?"true":"false";
	form.needAttachedSheet.value = "false";
	//订单附言
	form.orderPS.value = encodeURI($("#order_PS_VAL").val());
	//礼品订单
	var isGiftOrder = $(":checkbox[name='is_give_gift']").attr("checked")=="checked"?"true":"false";
	form.giftOrder.value = isGiftOrder;
	if(isGiftOrder == "true"){
		form.getGiftName.value = encodeURI($("#get_gift_name").val());
		form.giveGiftName.value = encodeURI($("#give_gift_name").val());
		var giveGiftMobile = $("#give_gift_mobile").val();
		form.giveGiftMobile.value = $("#give_gift_mobile").val();
		form.message.value = encodeURI($("#give_gift_note").val());
		form.invoiceTitle.value = "";
	}
	$(".submit-pro").html("<span>验证中，请稍候...</span>").show();
	jQuery.ajax({
		 type:'post',
		 url:'/order/beforeSubmit.htm',
		 data:myReplaceAll($("#_orderform").serialize(),'undefined',''),
		 dataType:'json',
		 contentType: "application/x-www-form-urlencoded; charset=utf-8",
		 async:true,
		 success:function(data){
			 if(data != null && data.message != null){
					if(data.message == "SUCCESS"){
						try{
							form.action=form.action+"?t="+new Date().getTime();
							$(".submit-pro").html("<span>处理中，请稍候...</span>").show();
							$(form).submit();
						}catch(err){
							removeDisabledButton();
							alert("Error message: " + err.message);
						}
					}else{
						if(data.messageType != null && data.messageType == "orderfail"){
							try{
								$("#message").val(encodeURI(data.message));
								removeDisabledButton();
								$("#_orderfailform").submit();
							}catch(err){
								removeDisabledButton();
								alert("Error message: " + err.message);
							}
						}else{
							$(".pop-wrap:eq(0) .pop-main").css({'height':'79px','padding-top':'41px'});
							if(data.message.indexOf("验证码") > 0){
								$(".popMask,.popBox").show();
								jQuery("#captchaImage2").attr("src", "http://public.jiuxian.com/public/captchaimg.htm?timestamp" + (new Date()).valueOf());
								$(".submit-pro").hide();
							}
							if(data.message.indexOf("快递停发") > 0){
								$(".alertContent").html(data.message);
								$(".pop-wrap:eq(0) .pop-main").css({'height':'109px','padding-top':'11px'});
								$(".btn1,.btn2").show();
								$(".btn3").hide();
								$("#pop-main-i").addClass("confirm");
								$("#pop-main-i").removeClass("alarm").show();
								$(".pop-modal:eq(0),.pop-wrap:eq(0)").show();
								$(".submit-pro").hide();
							}else if(data.message.indexOf("天气原因") > 0){
								$(".alertContent").html(data.message);
								$(".btn1,.btn2").hide();
								$(".btn3").show();
								$("#pop-main-i").removeClass("confirm");
								$("#pop-main-i").addClass("alarm").show();
								$(".pop-modal:eq(0),.pop-wrap:eq(0)").show();
								$(".submit-pro").hide();
							}else{
								if(data.stockoutGifts!=""){
									$("#stockoutGifts").val(data.stockoutGifts);
								}
								$(".submit-pro").html("<span>"+data.message+"</span>").show();
							}
							removeDisabledButton();
						}
					}
				}else{
					removeDisabledButton();
					alert("系统异常请稍后重试!");
				}
		 },
		 error:function(e){
			 removeDisabledButton();
			 alert("操作失败,请稍后重试!!!");
		 }
	});
}

function myReplaceAll(str, sptr, sptr1){
    while (str.indexOf(sptr) >= 0){
       str = str.replace(sptr, sptr1);
    }
    return str;
}

function removeDisabledButton(){
	$(".subBtn").css("background","#CF000D");
	$(".subBtn").removeAttr("a");
}
function refreshGoodsList(isFirstLoad,addressName){
	var regionid = $(".addressList .on input").attr("regionid");
	$("#goods_list_container").load("/order/loadGoodsList.htm",{"regionId":regionid,"productAccount":productAccount,"stockoutGifts":stockoutGifts,"addressName":encodeURI(addressName)},function(){

		if(isFirstLoad){
			var totalPrice = $("#totalPrice").val();
			$("#productcount").html($("#procount").val());
			var productPrice = $("#productPrice").val();
			$("#zje_i").html("￥"+productPrice);
			$("#jbcount").html($("#pointsCount").val());
			var priceCutAmount = $("#priceCutAmount").val();
			if(priceCutAmount != "" && priceCutAmount > 0){
				$("#yh_i").html("-￥"+priceCutAmount);
				$("#yh_div").show();
			}
			var forcxyh = $("#forcxyh").html();
			if(forcxyh != null && forcxyh != ""){
				$("#cxyhdetail").html(forcxyh);
				$("#cxyh").show();
			}
			var payPrice = totalPrice;
			var expensesPrice = returnFloat2(parseFloat($("#expensesPrice").val()));
			$("#yf_i").html("￥"+expensesPrice);
			$("#yf_div").show();
			payPrice = parseFloat(payPrice) + parseFloat(expensesPrice);
			if(payPrice>0){
				$("#fapiaoxinxi").removeAttr("disabled");
			}
			$("#toPayPrice").val(returnFloat2(parseFloat(payPrice)));
			$("#payPrice").html("￥"+returnFloat2(parseFloat(payPrice)));
			$("#productAccount").val(productAccount);
		}
		$("#stockoutGifts").val(stockoutGifts);
		//加载红包
		var isDisableCoupon = $("#disableCoupon").val();
		if(isDisableCoupon == "false"){
			searchCoupon();
		}else if(!isFirstLoad){
			changePayPrice();
		}
		setScrollTop();
		// 显示变更地址提示
//		var showAddressTips = $("#showAddressTips").val();
//		if(showAddressTips == 1){
//			$(".field-pro").show();
//		}
	});
}
function clearhtml(){
	$(".submit-pro").html("").hide();
}

//删除选中的
function delUserAddress(id){
	jQuery.ajax({
		 type:'post',
		 url:'/order/deleteUserAddress.htm',
		 data:{'id':id},
		 dataType:'json',
		 cache:false,
		 async:false,
		 success:function(data){
			 if(data == null || data.message == null || data.message == "" || data.message == "ERROR"){
				 alert("操作失败,请稍后重试!!!");
			 }else if(data.message == "DELETE_SUCCESS"){
				 //alert("删除成功!");
			 }
			 isFirstLoad = false;
			 getUserAddress(0);
		 },
		 error:function(){
			 alert("操作失败,请稍后重试!!!");
		 }
	 });
}

function getlenstr(str,lth,after)
{
	if(str==null){
		return 'null';
	}
	if(str==""||str=='undefined'){
		return str;
	}
var strlen = 0;
var restr = "";
	for(var i = 0;i < str.length; i++){
		if(str.charCodeAt(i) > 255) // 如果是汉字，则字符串长度加2
			strlen += 1.7;
		else
			strlen++;
		if(strlen>=lth){ restr=restr+after;break;}
		restr = restr + str.charAt(i);
	}
	return restr;
}
//获取用户地址列表
function getUserAddress(id){
	var defAddressID = $("#defAddressID").val();
	var lastAddressID = $("#lastAddressID").val();
	var islastselect = false;
	var select = false;
	if(id > 0&&id!=defAddressID){
		islastselect = true;
		lastAddressID = id;
	}
	jQuery.ajax({
		 type:'post',
		 url:'/order/getUserAddress.htm',
		 dataType:'json',
		 cache:false,
		 async:false,
		 success:function(data){
			$(".addressList").empty();
		 	if(data != null && data.list != null && data.list.length > 0){
				if(defAddressID != null && defAddressID != "" && defAddressID != undefined && defAddressID > 0){
					for(var i = 0;i<data.list.length;i++){
						if(data.list[i].ID == defAddressID){
							var consignee = getlenstr(data.list[i].consignee,7,'');
							var mobile = data.list[i].mobile;
							if(mobile==null||mobile==""){
								mobile = data.list[i].phone;
							}
							var addressMore = data.list[i].addressName + data.list[i].addressMore;
							addressMore = getlenstr(addressMore,62,'...');
							var itemclass = "item";
							if(!islastselect){
								itemclass = "item on";
								select = true;
							}
							var einv = data.list[i].supporteinv;
							var str = "<li class='"+itemclass+"' einv='"+einv+"'><input type='hidden' value='"+data.list[i].ID+"' addressname='"+data.list[i].addressName+"' regionid='"+data.list[i].regionId+"'/><div class='address-tit'><b>"+consignee+"</b><span>"+mobile+"</span></div>"
								+"<div class='address-con'>"+addressMore+"</div><div class='address-ope'><a class='addAlter' href='javascript:;' _di='"+data.list[i].ID+"'>修改</a><a class='addDelete' href='javascript:;' _di='"+data.list[i].ID+"'>删除</a></div>"
								+"<div class='defaultBtn'_di='"+data.list[i].ID+"' style='display:none'>设为默认地址</div><div class='addDefault oIcon defOn'></div></li>";
							$(".addressList").append(str);
						}
					}
					
				}
				if(defAddressID != lastAddressID){
					for(var i = 0;i<data.list.length;i++){
						if(data.list[i].ID==lastAddressID){
							var consignee = getlenstr(data.list[i].consignee,7,'');
							var mobile = data.list[i].mobile;
							if(mobile==null||mobile==""){
								mobile = data.list[i].phone;
							}
							var addressMore = data.list[i].addressName + data.list[i].addressMore;
							addressMore = getlenstr(addressMore,55,'...');
							var itemclass = "item";
							if(!select){
								itemclass = "item on";
								select = true;
							}
							var einv = data.list[i].supporteinv;
							var str = "<li class='"+itemclass+"' einv='"+einv+"'><input type='hidden' value='"+data.list[i].ID+"' addressname='"+data.list[i].addressName+"' regionid='"+data.list[i].regionId+"'/><div class='address-tit'><b>"+consignee+"</b><span>"+mobile+"</span></div>"
								+"<div class='address-con'>"+addressMore+"</div><div class='address-ope'><a class='addAlter' href='javascript:;' _di='"+data.list[i].ID+"'>修改</a><a class='addDelete' href='javascript:;' _di='"+data.list[i].ID+"'>删除</a></div>"
								+"<div class='defaultBtn' _di='"+data.list[i].ID+"'>设为默认地址</div><div class='addDefault oIcon'></li>";
							$(".addressList").append(str);
							break;
						}
					}
				}
				for(var i = 0;i<data.list.length;i++){
					if(data.list[i].ID == defAddressID || data.list[i].ID==lastAddressID){
						// 置顶了
					}else{
						var consignee = getlenstr(data.list[i].consignee,7,'');
						var mobile = data.list[i].mobile;
						if(mobile==null||mobile==""){
							mobile = data.list[i].phone;
						}
						var addressMore = data.list[i].addressName + data.list[i].addressMore;
						addressMore = getlenstr(addressMore,55,'...');
						var itemclass = "item";
						if(!select&&i==0){
							itemclass = "item on";
						}
						var einv = data.list[i].supporteinv;
						var str = "<li class='"+itemclass+"' einv='"+einv+"'><input type='hidden' value='"+data.list[i].ID+"' addressname='"+data.list[i].addressName+"' regionid='"+data.list[i].regionId+"'/><div class='address-tit'><b>"+consignee+"</b><span>"+mobile+"</span></div>"
							+"<div class='address-con'>"+addressMore+"</div><div class='address-ope'><a class='addAlter' href='javascript:;' _di='"+data.list[i].ID+"'>修改</a><a class='addDelete' href='javascript:;' _di='"+data.list[i].ID+"'>删除</a></div>"
							+"<div class='defaultBtn' _di='"+data.list[i].ID+"'>设为默认地址</div><div class='addDefault oIcon'></li>";
						$(".addressList").append(str);
					}
				}
				var addr = $(".addressList .on input").attr("addressname");
				if(addr!=null&&addr!=""&&addr!="underfind"){
					refreshGoodsList(true,addr);
				}else{
					refreshGoodsList(true,"北京市");
				}
				if(data.list.length >= 20){
					$(".orderAddress .addNewAdd").hide();
				}else{
				 	var str = "<li class='add'><div class='address-add'><i class='oIcon'></i><span>增加新地址</span></div></li>";
				 	$(".addressList").append(str);
					$(".orderAddress .addNewAdd").show();
				}
				if(data.list.length <= 3){
					$(".addressOpen").hide();
				}else{
					$(".addressOpen").show();
					//$(".addressList .add").insertAfter($(".addressList .item").eq(2));
				}
			}else{
			 	var str = "<li class='add'><div class='address-add'><i class='oIcon'></i><span>增加新地址</span></div></li>";
			 	$(".addressList").append(str);
				$(".orderAddress .addNewAdd").show();
				$(".addressOpen").hide();
				refreshGoodsList(true,"北京市");
			}
		 	if($(".item.on").attr("einv")=="true"){
		 		//默认地址支持电子发票
		 		choseInvoiceType(0);
		 		if($("input[name=inv_type]:checked").val()==2){
		 			showInvoiceType(2);
		 		}
		 	}else{
		 		//默认地址不支持电子发票
		 		choseInvoiceType(1);
		 		enableInvTitle();
		 		$(".invPhoneNum,.invPro").hide();
		 	}
		 	bindAddressClick();
		 	isSupportAliBillPay();
		 },
		 error:function(){
			 alert("操作失败,请稍后重试!!!");
		 }
	 });
	
}

function getRealPhone(phone){
	if(isHiddenPhone(phone)){
		return $("#real-mobile").val();
	}else{
		return phone;
	}
}
function isHiddenPhone(str){
	var realmobile = $("#real-mobile").val();
	var show= realmobile.substring(0,3)+"****"+realmobile.substring(8,11);
	return show == str;
}
function showPhoneIfRealHave(){
	var realmobile = $("#real-mobile").val();
	var show= realmobile.substring(0,3)+"****"+realmobile.substring(8,11);
	if(realmobile!=""){
		$("#inv_mobile").val(show);
	}
}
function showInvoiceType(type){
	if(type==2){
		//纸质
		$('.invPhoneNum,.invPro').hide();
		$('.invoiceTitWrap').removeClass("thresholder");
		$('.invoiceTitWrap').attr("enabled","true");
		$("#invoiceTitCon").removeAttr("disabled");
		if(defaultTitle!=""){
			$(".tholder").hide();
			$("#invoiceTitCon").val(defaultTitle);
		}
	}else if(type==1){
		//电子
		$('.invPhoneNum,.invPro').show();
		$('.invoiceTitWrap').addClass("thresholder");
		$('.invoiceTitWrap').attr("enabled","false");
		//TODO 后期要改  写死了只能是个人
		$("#invoiceTitCon").val("");
		$(".tholder").show();
		$("#invoiceTitCon").attr("disabled","disabled");
	}
}
//可以修改inv_title
function enableInvTitle(){
	$("#invoiceTitCon").removeAttr("disabled");
	$(".invoiceTitWrap").removeClass("thresholder").attr("enabled","true");
}
function disableInvTitle(){
	$("#invoiceTitCon").attr("disabled","disabled");
	$(".invoiceTitWrap").addClass("thresholder").attr("enabled","false");
}
function choseInvoiceType(type){
	if(type==1){
		//当前地址不支持电子发票
		$("input[name=inv_type]").removeAttr("checked");
		$("input[name=inv_type]").eq(INDEX_PAPER).attr("checked","checked");
		$("input[name=inv_type]").eq(INDEX_EINV).attr("disabled","disabled");
	}else{
		$("input[name=inv_type]").eq(INDEX_EINV).removeAttr("disabled");//.attr("checked","checked");
	}
}

function clickConSubmit(){
	var invtype = $("input[name=inv_type]:checked").val();
	var invoiceVal = $.trim($("#invoiceTitCon").val());
	var invoiceDetail = $("input[name=inv_con]:checked").attr("title");
	var invoiceKinds = $("input[name=inv_type]:checked").attr("title");
	var invoiceTitle = null;
	if(invoiceVal==''){
		invoiceTitle='个人';
	}else{
		invoiceTitle=invoiceVal;
	}
	if(invtype=="1"){
		//电子发票，验证手机号
		var $invPhone = $(".invPhone");
		var pattern=/^(13|14|15|18|17)[0-9]{9}$/;
		var phoValue = $.trim($invPhone.val());
		if(phoValue==''){
			$invPhone.next().text('请输入手机号').show();
			return false;
		}else if(!pattern.test(phoValue)&&!isHiddenPhone(phoValue)){
			$(this).next().text('请输入正确的手机号').show();
			return false;
		}
	}
	$(".orderInvoice .contentBox").hide();
	$(".orderInvoice .contentInfo .invoiceTitle").text(invoiceTitle);
	$(".orderInvoice .contentInfo .invoiceDetail").text(invoiceDetail);	
	$(".orderInvoice .contentInfo .invoiceKinds").text(invoiceKinds);
	$(".orderInvoice .contentInfo").show();
	$(".orderInvoice .modifyPayment").show();
}

//加载地址数据 港、澳、台不显示 
function loadAddress(id){
	jQuery.ajax({
		 type:'post',
		 url:'/order/loadAddress.htm',
		 data:{'id':id},
		 dataType:'json',
		 cache:false,
		 async:false,
		 success:function(data){
			 if(data != null && data.regListForm != null){
				var regListForm = data.regListForm;
				var content1 = [];
				content1.push('<option value="">请选择</option>');
				for(var i = 0;i<regListForm.firRegList.length;i++){
					if(regListForm.firRegList[i].ID != 33 && regListForm.firRegList[i].ID != 34 && regListForm.firRegList[i].ID != 35){
						content1.push('<option value="'+regListForm.firRegList[i].ID+'">'+regListForm.firRegList[i].name+'</option>');
					}
				}
				$("#new_province").empty().append(content1.join(''));
				var content2 = [];
				content2.push('<option value="">请选择</option>');
				for(var i = 0;i<regListForm.secRegList.length;i++){
				    content2.push('<option value="'+regListForm.secRegList[i].ID+'">'+regListForm.secRegList[i].name+'</option>');
				}	
				$("#new_city").empty().append(content2.join(''));
				var content3 = [];
				content3.push('<option value="">请选择</option>');
				for(var i = 0;i<regListForm.thiRegList.length;i++){
				    content3.push('<option value="'+regListForm.thiRegList[i].ID+'">'+regListForm.thiRegList[i].name+'</option>');
				}	
				$("#new_county").empty().append(content3.join(''));
				if(regListForm.regionId != 33 && regListForm.regionId != 34 && regListForm.regionId != 35){
					$("#new_province").val(regListForm.regionId);
				}
				$("#new_city").val(regListForm.pRegionId);
				$("#new_county").val(regListForm.ppRegionId);
			 }
		 },
		 error:function(){
			 alert("操作失败,请稍后重试!!!");
		 }
	 });
}

function len(s) {
	return s.length;
}
//切换省
function selProvinces(){
   var pId = jQuery.trim($("#new_province").val());
   if(pId != ''){
        var jsonData  =  getNextRegionList(pId);
		if(jsonData != null && jsonData.list != null && jsonData.list.length > 0){
            var content = [];
			content.push('<option value="">请选择</option>');
			$("#new_county").empty().append(content.join(''));
			for(var i = 0;i<jsonData.list.length;i++){
				content.push('<option value="'+jsonData.list[i].ID+'">'+jsonData.list[i].name+'</option>');
			}	
			$("#new_city").empty().append(content.join(''));
		}
   }
}
//切换市
function selCities(){
       var pId = jQuery.trim($("#new_city").val());
	   if(pId != ''){
	        var jsonData  =  getNextRegionList(pId);
			if(jsonData != null && jsonData.list != null && jsonData.list.length > 0){
		            var content = [];
					content.push('<option value="">请选择</option>');
					for(var i = 0;i<jsonData.list.length;i++){
					    content.push('<option value="'+jsonData.list[i].ID+'">'+jsonData.list[i].name+'</option>');
					}	 
					$("#new_county").empty().append(content.join(''));
			}
	   }
}
//获取省市区数据
function getNextRegionList(pId){
      var jsonData = null;
      jQuery.ajax({
		 type:'post',
		 url:'/getNextRegionList.htm',
		 data:{'pId':pId},
		 dataType:'json',
		 cache:false,
		 async:false,
		 success:function(data){
		     jsonData = data;            
		 },
		 error:function(){
			 alert("操作失败,请稍后重试!!!");
		 }
	 });
	 return jsonData;
}

function znqVerificationCode($obj){
	var $this = $obj;
	var znqVerificationCode = $("#znqVerificationCode").val();
	var reg = /^[0-9a-zA-Z]+$/;
	if(znqVerificationCode == undefined || $.trim(znqVerificationCode) == ''){
		$(".popCode-pro").html("请输入验证码！");
		return false;
	}else if($.trim(znqVerificationCode).length != 4){
		$(".popCode-pro").html("验证码格式不正确！");
		return false;
	}else if(!reg.test($.trim(znqVerificationCode))){
		$(".popCode-pro").html("验证码格式不正确！");
		return false;
	}else{
		$(".popMask,.popBox").hide();
		$("#znqVerificationCode").val(znqVerificationCode);
		return true;
	}
}

var addressSubmitStatus1 = false; //地址能否提交状态	
var addressSubmitStatus3 = false;//地址能否提交状态	
var addressSubmitStatus4 = false; //地址能否提交状态	
$(function(){
	showPhoneIfRealHave();
	if($("input[name=inv_type]:checked").val()==2){//默认纸质则取消手机输入
		$(".invPhoneNum,.invPro").hide();
	}
	//验证码
	jQuery("#_captchaImage").click( function() {
		captchaImage();
	});
	jQuery("#_captchaImage2").click( function() {
		captchaImage2();
	});
	jQuery("#captchaImage2").click( function() {
		captchaImage2();
	});
	
	$(".popCodeBut").bind('click',function(){
		znqVerificationCode($(this));
	});
	//送货地址
	$("body").click(function(e){
		$(".depit_citydrp").hide();
		$(".dOrder-city-sel").removeClass("dOrder_city_on");
	});
	$(".depit_citydrp").click(function(event){
		event.stopPropagation();
	});	
	$(".dOrder-city-sel").click(function(event){
		event.stopPropagation();
		$(this).addClass('dOrder_city_on');
		$(".depit_citydrp").show();
		
		$(".h5_dptctdrp a").removeClass("h5_dptdrp_on");
		$(".h5_dptctdrp a").eq(0).addClass("h5_dptdrp_on");
		$(".dptctdrp_list").hide();
		$(".dptctdrp_list").eq(0).show();
	});
	//展开地址
	$(".orderAddress .addressOpen").bind("click",function(){
		var text = $(this).find("b").text();
		if(text=="展开"){
			$(".orderAddress .addressList").css("height","auto");
			$(this).addClass("on");
			$(this).find("b").text("收起");
		}else{
			$(".orderAddress .addressList").css("height","139px");
			$(this).removeClass("on");
			$(this).find("b").text("展开");
			getUserAddress($(".addressList .on input").val());
		}
		setScrollTop();
	});

//   $('.zhifu').click(function(){
//      $(".paymentMode1").show();
//	  $(this).parents('li').addClass('selected').siblings().removeClass('selected');
//   })
   
//   $('.paymentMode1 .payMore').click(function(){
//		var payIndex = $('.paymentMode1 .payMore').index($(this));
//		$(this).addClass("on");
//		$(this).siblings(".payMore").removeClass("on");
//		$(".paymentMode2").show();
//		$(".paymentMode2 h4,.paymentMode2 ul").hide();
//		$(".paymentMode2 h4").eq(payIndex).show();
//		$(".paymentMode2 ul").eq(payIndex).show();
//   })
   
//   $('#huodaofukuan').click(function(){
//        $(".paymentMode1").hide();
//        $(".paymentMode1 .payMore").removeClass("on");
//		$(".paymentMode2").hide();
//		$(".paymentMode2 h4,.paymentMode2 ul").hide();
//		$(this).parents('li').addClass('selected').siblings().removeClass('selected');
//   })
	
   //其他支付
//   $("#qitazhifu").click(function(){
//       $(".paymentMode1").hide();
//       $(".paymentMode1 .payMore").removeClass("on");
//	   $(".paymentMode2").hide();
//	   $(".paymentMode2 h4,.paymentMode2 ul").hide();
//	   $('#huodaofukuan').removeClass('selected');
//	   $('#zxzf').removeClass('selected');
//	   $(this).parents("li").addClass('selected').siblings().removeClass('selected');
//   })
   
//   $('.paymentMode2 input').click(function(){
//        var back=$(this).parents('li').attr('name');
//	    $("#logo").attr('style',back);
//	    $("#logo").prev().attr('checked',true);
//		$('.paymentMode1').show();
//	    $('.paymentMode2').hide();
//	    $(".paymentMode1 .payMore").removeClass("on");
//	    $(".paymentMode2 h4,.paymentMode2 ul").hide();
//   })
	
	//促销优惠
	$("#cuxiaoyouhui").toggle(function(){
	    $('.settlementCon').hide();
		$(this).find("i").removeClass("off").addClass("on");
		setScrollTop();
	},function(){
		$('.settlementCon').show();
		$(this).find("i").removeClass("on").addClass("off");
		setScrollTop();
	});	
	
	//使用酒仙礼品卡
	$("#shiyongjiuxianlipk").toggle(function(){
	    $('#jiuxian').show();
		setScrollTop();
		$(this).find("i").removeClass("on").addClass("off");
	},function(){
		$('#jiuxian').hide();		
		$(this).find("i").removeClass("off").addClass("on");
		setScrollTop();
	});
	
	//使用余额返现
	$("#yue").toggle(function(){
	    $('#balanceWrap').show();
		$(this).find("i").removeClass("on").addClass("off");
		setScrollTop();
	},function(){
	    $('#balanceWrap').hide();
		$(this).find("i").removeClass("off").addClass("on");
	    setScrollTop();
	})
	
	//使用红包
	$("#hongbao").toggle(function(){
	  $("#youhunjuan").show();
	  $(this).find("i").removeClass("on").addClass("off");
	  setScrollTop();
	},function(){
	  $("#youhunjuan").hide();
	  $(this).find("i").removeClass("off").addClass("on");
	  setScrollTop();
	});
	
	//留言信息
	$("#leaveComments").toggle(function(){
		$("#liuyanxinxi").show();
		$(this).find("i").removeClass("on").addClass("off");
		setScrollTop();
	},function(){
		$("#liuyanxinxi").hide();
		$(this).find("i").removeClass("off").addClass("on");
		setScrollTop();
	});
	
	var gcTitNub=0;
	$(".giftCardTitleWrap .giftCardTitle").bind('click',function(){
		gcTitNub = $(".giftCardTitleWrap .giftCardTitle").index($(this));
		$(".giftCardTitleWrap .giftCardTitle").removeClass("gctitOn");
		$(this).addClass("gctitOn");
		$(".giftCardCon .giftCardBox").hide();
		$(".giftCardCon .giftCardBox").eq(gcTitNub).show();
		setScrollTop();
	})
	
	$(".stqBut").toggle(function(){
		$(this).parent(".giftCardStqTit").siblings(".giftCardStq").show();
		setScrollTop();
	},function(){
		$(this).parent(".giftCardStqTit").siblings(".giftCardStq").hide();
		setScrollTop();
	})
	
	$(".addresPopBox .popClose ").bind("click",function(e) {
        $(".addresPopBox,.popMask").hide();
		$(".addresPopBox .addPopCon .addPro").hide(); 
		$(".addresPopBox .addPopCon input").removeClass('on');
		addressSubmitStatus1=false; //地址能否提交状态	
		addressSubmitStatus3=false; //地址能否提交状态	
		addressSubmitStatus4=false; //地址能否提交状态
    });
	
	$(".orderBox").live("click",function(){
		$(".field-pro").show();
		var flag=$(this).parent(".orderItem").hasClass("first");
		if(flag){
			$(".field-pro").hide();
		}
		$(this).parent().addClass("on");
		$(this).parent().siblings().removeClass("on");
		$(this).parent().prependTo($(".orderAddress"));
	})
	//确定新增收货地址
	$(".addSubmit").click(function(e) {
		var consignee = $.trim($("#new_username").val());
		var new_province = $("#new_province option:selected").val();
		var new_city = $("#new_city option:selected").val();
		var new_county = $("#new_county option:selected").val();
		var addressMore = $("#new_detail").val();
		var zipcode = $("#new_postcode").val();
		var mobile = $.trim($("#new_phone").val());
		var tel = $("#new_tele").val();
		var addressName = $("#new_province option:selected").text()+"-"+$("#new_city option:selected").text()+"-"+$("#new_county option:selected").text();
		if(!addressSubmitStatus1){
			$("#new_username").addClass("on").siblings(".addPro").show();
			return false;
		}
		if (jQuery.trim(new_province) == "" || jQuery.trim(new_city) == "" || jQuery.trim(new_county) == "") {
			$("#new_province").siblings(".addPro").text("请您填写完整的地区信息").show();
			return false;
		}
		if(!addressSubmitStatus3){
			$("#new_detail").addClass("on").siblings(".addPro").show();		
			return false;
		}
		if(!addressSubmitStatus4){
			$("#new_phone").addClass("on").siblings(".addPro").show();		
			return false;
		}
		
		var id = $("#ID").val();
		if(id==undefined || id=="" || id<0){
			id = 0;
		}
		jQuery.ajax({
			 type:'post',
			 url:'/order/updateUserAddress.htm',
			 data:{'id':jQuery.trim(id),'consignee':encodeURI(jQuery.trim(consignee)),'rgn_RegionID':jQuery.trim(new_county),'addressName':encodeURI(jQuery.trim(addressName)),'addressMore':encodeURI(jQuery.trim(addressMore)),'zipcode':jQuery.trim(zipcode),'mobile':jQuery.trim(mobile),'phone':jQuery.trim(tel)},
			 dataType:'json',
			 contentType: "application/x-www-form-urlencoded; charset=utf-8",
			 cache:false,
			 async:false,
			 success:function(data){
				 if(data!=null && data.state==1){
					 alert("您最多只能添加20个地址。");
					 return false;
				 }else if(data == null || data.message == null || data.message == "" || data.message == "ERROR"){
					 alert("操作失败,请稍后重试!!!");
					 $(".addresPopBox,.popMask").hide();
					 $(".submit-pro").hide();
					 $(".subBtn").css("background","#CF000D");
					 $(".subBtn").removeAttr("a");
					 isFirstLoad = false;
					 getUserAddress(id);
				 }else if(data.message == "INSERT_SUCCESS"){
					 $(".addresPopBox,.popMask").hide();
					 $(".submit-pro").hide();
					 $(".subBtn").css("background","#CF000D");
					 $(".subBtn").removeAttr("a");
					 isFirstLoad = false;
					 getUserAddress(data.addressId);
				 }else if(data.message == "UPDATE_SUCCESS"){
					 $(".addresPopBox,.popMask").hide();
					 $(".submit-pro").hide();
					 $(".subBtn").css("background","#CF000D");
					 $(".subBtn").removeAttr("a");
					 isFirstLoad = false;
					 getUserAddress(id);
				 }else{
					 if(data.messageType != null && data.messageType != ""){
						 $("#alertstyle" + data.messageType).html(data.message);
						 $("#alertstyle" + data.messageType).show();
					 } else {
						 alert(data.message);
					 }
					 return false;
				 }
			 },
			 error:function(){
				 alert("操作失败,请稍后重试!!!");
			 }
		 });
		if(jQuery.trim(id) !=""){//修改地址时才向erp同步
			jQuery.ajax({
				 type:'get',
				 url:'/order/updateUserAddressToErp.htm',
				 data:{'id':jQuery.trim(id),'consignee':encodeURI(jQuery.trim(consignee)),'rgn_RegionID':jQuery.trim(new_county),'addressName':encodeURI(jQuery.trim(addressName)),'addressMore':encodeURI(jQuery.trim(addressMore)),'zipcode':jQuery.trim(zipcode),'mobile':jQuery.trim(mobile),'phone':jQuery.trim(tel)},
				 dataType:'json',
				 cache:false,
				 success:function(data){
					 
				 }
			 });
		}
    }); 
	
	 /*收货人*/
	 $("#new_username").bind("blur",function(){
			var value = $.trim($(this).val());
			var reg=/[;\/<>\*"'\.~=\+\^%\$@&{}\\]+/g;	
			if(value==""){
				$(this).addClass("on").siblings(".addPro").text("请填写收货人姓名").show();		
				addressSubmitStatus1 = false;
			}else{
				if(reg.test(value)){
					$(this).addClass("on").siblings(".addPro").text("收货人姓名中含有非法字符").show();		
					addressSubmitStatus1 = false;
				}else{
					$(this).removeClass("on").siblings(".addPro").hide();
					addressSubmitStatus1 = true;
				}				
			}
		});
	
	/*详细地址*/
	$("#new_detail").bind("blur",function(){
		var value = $.trim($(this).val());
		var reg=/[;\/<>\*"'\.~=\+\^%\$@&\\]+/g;	
		if(value==""){
			$(this).addClass("on").siblings(".addPro").text("请填写收货人详细地址").show();		
			addressSubmitStatus3 = false;
		}else{
			if(reg.test(value)){
				$(this).addClass("on").siblings(".addPro").text("收货人地址中含有非法字符").show();		
				addressSubmitStatus3 = false;
			}else{
				$(this).removeClass("on").siblings(".addPro").hide();
				addressSubmitStatus3 = true;
			}				
		}
	});
	 
	//收货人电话
		$("#new_phone,#new_tele").bind("blur",function(){
			var addPopTit = $(".addresPopBox .addPopTit strong").html();
			var value1 = $.trim($("#new_phone").val());
			var value2 =$.trim($("#new_tele").val());
			var reg1=/^(1(3|4|5|7|8)[0-9]{9})$|^([0-9]{3}\*{4}[0-9]{4})$/;
			var reg2=/^([0-9]{1,}-?[0-9]{1,})$|^([0-9]{2}\*{3}[0-9]{1,})$|^([0-9]{1,}-[0-9]{2}\*{3}[0-9]{1,})$/;
			if(addPopTit=='新增地址'){
				reg1 = /^(1(3|4|5|7|8)[0-9]{9})$/;
			}
			if(addPopTit=='新增地址'){
				reg2 = /^[0-9]{1,}-?[0-9]{1,}$/;
			}
			if(value1==""){
				$(this).addClass("on").siblings(".addPro").text("请填写手机号码").show();		
				addressSubmitStatus4 = false;
			}else{
				if(value1!=""&&!reg1.test(value1)){
					$(this).addClass("on").siblings(".addPro").text("请填写正确的手机号码").show();		
					addressSubmitStatus4 = false;
				}else if(value2!=""&&!reg2.test(value2)){
					$(this).addClass("on").siblings(".addPro").text("请填写正确的固话").show();		
					addressSubmitStatus4 = false;
				}else{
					$(this).siblings(".addPro").hide();
					$("#new_phone,#new_tele").removeClass("on");
					addressSubmitStatus4 = true;
				}				
			}
		});
		
		$("#new_phone").bind("focus",function(){
			var phone = $(this).val();
			if(phone !=null && phone.indexOf("*")>-1){
				$(this).val('');
			}
		});
		
		$("#new_tele").bind("focus",function(){
			var tele = $(this).val();
			if(tele !=null && tele.indexOf("*")>-1){
				$(this).val('');
			}
		});
		
		$(".addPopCon input").bind("focus",function(){
			$(this).removeClass("on").siblings(".addPro").hide();
		});
     
	 $(".giftCard .open").live("click",function(){
			var text=$(this).text();
			if(text=="展开"){
				$(this).parent().css("height","auto");
				$(this).parent().css("overflow","visible");
				$(this).text("收起")
			}else{
				$(this).parent().css("height","130px");
				$(this).parent().css("overflow","hidden");
				$(this).text("展开")
			}
			setScrollTop();
	    });

	
	
	//提交按钮
	$(".subBtn").click(function(e) {
		var inv_chk =  $(":radio[name='InvoiceCustom']:checked").val();
		var isGiftOrder = $(":checkbox[name='is_give_gift']").attr("checked")=="checked"?"true":"false";
		if(isGiftOrder != "true"){
			if($("#fapiaoxinxi").attr("checked")=='checked' && $(".orderInvoice .contentBox").css('display')=='block'){
				$(".submit-pro").html("<span>您需要先保存<a href='#inv_href'>发票信息</a>，再提交订单</span>").show();
				return false;
			}
		}
		if($(".orderGift .contentBox").css('display')=='block'){
			$(".submit-pro").html("<span>您需要先保存<a href='#gift_href'>礼品订单信息</a>，再提交订单</span>").show();
			return false;
		}
        if($(".addressList .on").html()==null){
			$(".submit-pro").html("<span>您需要先选择<a href='#'>收货人信息</a>，再提交订单</span>").show();
			return false;		
		}
    	var reg=/[;\/<>\*"'\.~=\+\^%\$@&{}\\]+/g;
    	if(reg.test($("#order_PS_VAL").val())){
    		$(".submit-pro").html("<span>留言信息包含非法字符</span>").show();
    		return false;
    	}else{
			refreshFormData();
		}
    });	
	
	//礼品卡密码框切换事件
	$("#lpkpw1,#lpkpw2,#lpkpw3,#lpkpw4").keyup(function(){
		$(this).val($(this).val().replace(/[\W]/g,''));	//replace(/[^\d]/g,'')数字
		if($(this).val().length==4 && $(this).attr('_di') < 4){
			$("#lpkpw"+(parseInt($(this).attr('_di'))+parseInt(1))).focus();
		}
	});
	$("#lpksn,#identifyingCode,#account").keyup(function(){
		$(this).val($(this).val().replace(/[^A-Za-z0-9-]/g,''));	//replace(/[^\d]/g,'')数字
	});
	//余额只允许输入0-9
	$("#accoutMoneyInput").keyup(function(){
		if(($(this).val().indexOf(".") > -1 && $(this).val().indexOf(".") + 1 == $(this).val().length) || ($(this).val().indexOf(".0") > -1 && $(this).val().indexOf(".0") + 2 == $(this).val().length)){}else {
			var values = $(this).val();
			if(values.indexOf(".") > -1 && values.indexOf(".")+3 < values.length){
				values = values.substring(0,values.indexOf(".") + 3);
			}
			var num = parseFloat(values);
			if(num>=0){
				if($("#userAccoutFund").html()>=num){
					$(this).val(num);
				}else{
					$(this).val(parseFloat($("#userAccoutFund").html()));
				}
			}else{
				$(this).val("0");
			}
			changePayPrice();
		}
	});
	//返现只允许输入0-9
	$("#cashbackInput").keyup(function(){
		if(($(this).val().indexOf(".") > -1 && $(this).val().indexOf(".") + 1 == $(this).val().length) || ($(this).val().indexOf(".0") > -1 && $(this).val().indexOf(".0") + 2 == $(this).val().length)){}else {
			var values = $(this).val();
			if(values.indexOf(".") > -1 && values.indexOf(".")+3 < values.length){
				values = values.substring(0,values.indexOf(".") + 3);
			}
			var num = parseFloat(values);
			if(num>=0){
				if($("#userAccoutBack").html()>=num){
					$(this).val(num);
				}else{
					$(this).val(parseFloat($("#userAccoutBack").html()));
				}
			}else{
				$(this).val("0");
			}
			changePayPrice();
		}
	});

	$("#accoutMoneyInput,#cashbackInput").blur(function(){
		if($(this).val().indexOf(".") > -1 && $(this).val().indexOf(".") + 1 == $(this).val().length){
			$(this).val($(this).val().substring(0,$(this).val().indexOf(".")));
		}
	});
	$("#inv_payee").removeAttr("disabled");
	$("#useBtn2").click(function(){
		return checkPassword();
	});
	//选择红包计算支付金额
	$(".bonus").live("click",function(){
		changePayPrice();
		clearhtml();
	});
	$("#redEnvelope").hide();
	$("#couponTr").hide();

	//用户绑定红包
	$("#checkCoupon").click(function(){
		var account = jQuery.trim($("#account").val());
		var identifyingCode = jQuery.trim($("#identifyingCode").val());
		if(account == ""){
			$("#alertstyle8").html("请填写红包序列号!");
			$("#account").focus();
			return false;
		}
		if(identifyingCode == ""){
			$("#alertstyle8").html("请填验证码!");
			$("#account").focus();
			return false;
		}
		jQuery.ajax({
			 type:'post',
			 url:'/order/bindingCoupon.htm',
			 data:{'account':account,'identifyingCode':identifyingCode},
			 dataType:'json',
			 cache:false,
			 async:false,
			 success:function(data){
			 	if(data != null && data.enty != null && data.message != null && data.message == "SUCCESS"){
					var canUseNum = $("#canUseNumInput").val();
					canUseNum = parseFloat(canUseNum)+1;
					$("#canUseNum").html("("+canUseNum+")");
					$("#canUseNumInput").val(canUseNum);
					$("#useCouponList").append("<span><input type='radio' value='"+data.enty.ID+"' class='bonus' name='bonus' _di='"+data.enty.price+"'/><em class='ggname'>"+data.enty.Name+"[￥"+data.enty.price+".00]</em><em>有效期至"+data.enty.BlankOutTime+"</em></span>");
					$("#account").val("");
					$("#alertstyle8").html("");
					$(".giftCardStq").hide();
					$("#identifyingCode").val("");
					captchaImage();
					changePayPrice();
					searchCoupon();
					$.showAlert({"title":"提示","content":"红包绑定成功!", "type":"alarm"});
			 	}else{
			 		if(data.message != null && data.message == "ERROR"){
			 			$("#alertstyle8").html("该红包不存在!");
			 			$("#identifyingCode").val("");
			 			captchaImage();
			 		}else if(data.message != null && data.message == "IDENTIFYINGCODE_ERROR"){
			 			$("#alertstyle8").html("验证码错误!");
			 			$("#identifyingCode").val("");
			 			captchaImage();
			 		}
				}
			 	setScrollTop();
			 },
			 error:function(){
				 alert("操作失败,请稍后重试!!!");
			 }
		 });
	});
	//选中礼品卡
	$("input[name='giftCards']").live("click",function(){
		$("[name='giftCards']").each(function(){
			 if(!$(this).attr("checked")){
				 if($(this).attr('_di') != undefined){
					 var id = $(this).attr("id");
					 $("#"+id+"_SHIYONG").text("0.00元");
					 $("#"+id+"_SHENGYU").text("0.00元");
				 }
			 }
		});
		changePayPrice();
	});
	$("#giftTabBox ,#giftTabTit").hide();
	//添加礼品卡
	$("#useBtn1").click(function(){
		var giftCardCard = jQuery.trim($("#lpksn").val());
		if(giftCardCard == ""){
			$("#alertstyle6").html("请填写礼品卡卡号!");
			$("#lpksn").focus();
			return false;
		}
		var giftCardPass = jQuery.trim($("#lpkpw1").val()) + jQuery.trim($("#lpkpw2").val()) + jQuery.trim($("#lpkpw3").val()) +jQuery.trim($("#lpkpw4").val());
		if(giftCardPass == ""){
			$("#alertstyle6").html("请填写礼品卡密码!");
			$("#lpkpw1").focus();
			return false;
		}
		jQuery.ajax({
			 type:'post',
			 url:'/order/searchGiftCard.htm',
			 data:{'card':giftCardCard,'pass':jQuery.trim(giftCardPass)},
			 dataType:'json',
			 cache:false,
			 async:false,
			 success:function(data){
				 if(data == null || data.message == null || data.message == "" || data.message == "ERROR"){
					 alert("操作失败,请稍后重试!!!");
				 }else{
					 if(data.message == "SUCCESS"){
						 var isAdd = true;
						 $("[name='giftCards']").each(function(){
							 if($(this).val() == giftCardCard+"_"+giftCardPass){
								 isAdd = false;
								 $("#alertstyle6").html("该礼品卡已存在!");
							 }
						 });
						 if(isAdd){
							 $("#alertstyle6").html("");
							 $("#lpksn").val("");
							 $("#lpkpw1").val("");
							 $("#lpkpw2").val("");
							 $("#lpkpw3").val("");
							 $("#lpkpw4").val("");
							 //卡号,面值,当前可用金额,本订单使用,支付后剩余,到期时间,类型
							 var typeStr = data.giftCard.binDingType?"已绑定":"未绑定";
							 $("#giftTabBox ,#giftTabTit").show();
							 $("#lpksp").append("<tr><td><input name='giftCards' id='"+giftCardCard+"' type='checkbox' value='"+giftCardCard+"_"+giftCardPass+"' _di='"+data.giftCardDetail.remaindPrice+"'/>&nbsp;"+data.giftCardDetail.account+"</td><td>"+returnFloat2(data.giftCard.cartPrice)+"元</td><td>"+returnFloat2(data.giftCardDetail.remaindPrice)+"元</td><td id='"+giftCardCard+"_SHIYONG'>0.00元</td><td id='"+giftCardCard+"_SHENGYU'>0.00元</td><td>"+data.dataformat+"</td><td>"+typeStr+"</td></tr>");
							 $("#"+giftCardCard).click();
							 changePayPrice();
						 }
					 }else{
						 $("#alertstyle6").html(data.message);
					 }
				 }
				 setScrollTop();
			 },
			 error:function(){
				 alert("操作失败,请稍后重试!!!");
			 }
		 });
	});
	$("#new_province").change(function(){
		selProvinces();
	});
	$("#new_city").change(function(){
		 selCities();
	});
	$("#new_county").change(function(){
		 if($("#new_county option:selected").val()==""){
			 $(this).siblings(".addPro").show();
			 return false;
		 }
		 $(this).siblings(".addPro").hide();
	});
	
	getUserAddress(0);
//	var payment = $(":radio[name='_payment']:checked").attr("_data");
//	if(payment == undefined || payment == ""){
//		$('input:radio[name="_payment"][_data="101"]').click();
//		if($("#huodaofukuan").attr('checked') == "checked"){
//			$('#huodaofukuan').click();
//		}else if($("#qitazhifu").attr('checked') == "checked"){
//			$('#qitazhifu').click();
//		}
//	}
	
	//留言信息
	$(".paymentWrapLam .form-8").bind('focus',function(){
		$(this).siblings("span").hide();
		$(this).removeClass("on").parent().siblings('.conPro01').hide();
		clearhtml();
	})
	$(".paymentWrapLam .form-8").bind('blur',function(){
		var reg=/[;\/<>\*"'\.~=\+\^%\$@&{}\\]+/g;
		if($.trim($("#order_PS_VAL").val()) == ""){
			$(this).siblings("span").show();
		}else if(reg.test($.trim($("#order_PS_VAL").val()))){
			$(this).addClass("on").parent().siblings('.conPro01').css("display","inline-block");
		}
	})
	
	$(".paymentWrapLam .psValBg span").bind('click',function(){
		$(this).hide();
		$(".paymentWrapLam .form-8").focus();
	});
	
	/*发票信息start*/
	$("input[name='inv_type']").change(function(){
		var invoiceDetail = $("input[name='inv_type']:checked").attr("title");
		if(invoiceDetail=='纸质发票'){
			showInvoiceType(2);
		}else if(invoiceDetail=='电子发票'){
			showInvoiceType(1);
		}
	});
	$(document).bind('click',function(event){
		$('.invTitleBox').hide();
		event.stopPropagation();
	});
	$('.invoiceTitWrap input').bind('focus',function(){
		var enabled = $(this).parent().attr('enabled');
		if(enabled=="true"){
			$(this).siblings('.invTitleBox').show().siblings('.tholder').hide();
		}else{
			return;	
		}
	});
	$('.invTitleBox li').bind('click',function(){
		var tex = $(this).text();
		$(this).parents('.invTitleBox').hide().siblings('input').val(tex);
		$(this).parents('.invTitleBox').siblings('.tholder').hide();
	});
	$(".titOpen").bind('click',function(){
		var enabled = $(this).parent().attr('enabled');
		if(enabled=="true"){
			$(this).siblings('.invTitleBox').show();
		}else{
			return;	
		}
	});
	
	$(".invoiceTitWrap").bind('click',function(event){
		var enabled = $(this).attr('enabled');
		if(enabled=="true"){
			event.stopPropagation();
		}else{
			return;	
		}
	});
	
	$('.invoiceTitWrap .tholder').bind('click',function(){
		$(this).siblings('input').focus();
		$(this).siblings('.invTitleBox').show();
	});
	$('.invTitleBox li:last').css('border-bottom','none');
	$('.invTitleBox').each(function() {
		var invNum=$(this).find('li').length;
        if(invNum>3){
			$(this).css('height','80px').find('ul').css('height','80px');
		}else{
			$(this).css('height','80px').find('ul').css('height','auto');
		}
    });
	$(".orderInvoice .fapiaoxinxi").bind("click",function(e) {
		var status = $(this).attr("checked");
		if(status == "checked"){
			if($(".invTitleBox ul li").size()>0){//has history invoice,onclick noshow.
				clickConSubmit();
			}else{
				$(".orderInvoice .contentBox").show();
			}
			hasViewedInvo = true;
		}else{
			var invoiceDetail = $("input[name='inv_type']:checked").attr("title");
			if(invoiceDetail=='纸质发票'){
				$('.invPhoneNum,.invPro').hide();
				$('.invoiceTitWrap').removeClass("thresholder");
				$('.invoiceTitWrap').attr("enabled","true");
				$("#invoiceTitCon").removeAttr("disabled");
			}else if(invoiceDetail=='电子发票'){
				$('.invPhoneNum,.invPro').show();
				$('.invoiceTitWrap').addClass("thresholder");
				$('.invoiceTitWrap').attr("enabled","false");
				$("#invoiceTitCon").attr("disabled","disabled");
			}
			$(".orderInvoice .contentBox").hide();
			$(".orderInvoice .modifyPayment,.orderInvoice .contentInfo").hide();
		}
    });
	
	$(".orderInvoice .modifyPayment").bind("click",function(e) {
		$(".orderInvoice .contentBox").show();
		$(".orderInvoice .contentInfo").hide();
    });
	
	$(".orderInvoice .invPhone").bind("blur",function(e) {
		var pattern=/^(13|14|15|18|17)[0-9]{9}$/;
		var phoValue = $.trim($(this).val());
		if(phoValue=='')
		{
			$(this).next().text('请输入手机号').show();
		}
		else if(!pattern.test(phoValue))
		{
			if(!pattern.test(phoValue)&&!isHiddenPhone(phoValue)){
				$(this).next().text('请输入正确的手机号').show();
			}
		}
		else
		{
			$(this).next().hide();
		}
    });

	$("#conSubmit").bind("click",clickConSubmit);
	
	
	$(".invoiceTitWrap input").bind("blur",function(e) {
		var value = $.trim($(this).val());
		if(value==""){
			$(this).next().css("display","inline-block");
			$(this).siblings('.conPro01').css("display","none");
			return false;
		}
		var reg=/[;\/<>\*"'\.~=\+\^%\$@&{}\\]+/g;
		if(reg.test(value)){
			$(this).next().css("display","none");
			$(this).siblings('.conPro01').html('单位信息包含非法字符').css("display","inline-block");
			return false;
		}
    });
	
	/*$(".orderInvoice .conSubmit").bind("click",function(){
		$(".submit-pro").hide();
		var invoiceTitle = "";
		if($(":radio[name='InvoiceCustom']:checked").val()==1){
			invoiceTitle = "个人";
		}else{
			invoiceTitle = $.trim($(".orderInvoice .conFrom01").val());
		}
		if(invoiceTitle==""){
			$("#inv_title").addClass("on").next().html('请填写单位信息').css("display","inline-block");
			return false;
		}
		var reg=/[;\/<>\*"'\.~=\+\^%\$@&{}\\]+/g;
		if(reg.test(invoiceTitle)){
			$("#inv_title").addClass("on").next().html('单位信息包含非法字符').css("display","inline-block");
			return false;
		}
		var invoiceDetail = $(".orderInvoice input[name=inv_con]:checked").attr("title");
		$(".orderInvoice .contentInfo .invoiceTitle").text(invoiceTitle);
		$(".orderInvoice .contentInfo .invoiceDetail").text(invoiceDetail);
		$(".orderInvoice .contentBox").hide();
		$(".orderInvoice .contentInfo").show();
		$(".orderInvoice .modifyPayment").show();	
	});*/
	
	/*发票信息end*/

	/*礼品订单start*/
	$(".orderGift .lipindingdan").bind("click",function(e) {
		var status = $(this).attr("checked");
		if(status == "checked"){
			$(".orderGift .contentBox").show();	
			$(".orderInvoice").hide();
		}else{
			$(".submit-pro").hide();
			$(".orderGift .contentBox").hide();	
			$(".orderGift .modifyPayment,.orderGift .contentInfo").hide();
			$(".orderInvoice").show();
		}
		setScrollTop();
    });
	$(".orderGift .modifyPayment").bind("click",function(e) {
		$(".orderGift .contentBox").show();
		$(".orderGift .contentInfo").hide();
    });
	$(".orderGift .giftPhone").bind("blur",function(){
		var value = $.trim($(this).val());
		if(value==""){
			$(this).addClass("on").siblings(".conPro01").css("display","inline-block");
			return false;
		}
		var reg = /^1[3|4|5|7|8][0-9]{9}$/;
		if(value!=""&&!reg.test(value)){
			$(this).addClass("on").siblings(".conPro01").css("display","inline-block");		
		}
	});
	$(".orderGift .contentBox .giftName01").bind("blur",function(){
		var reg=/[;\/<>\*"'\.~=\+\^%\$@&{}\\]+/g;
		var value = $.trim($(this).val());
		if(value==""){
			$(this).addClass("on").siblings(".conPro01").html('请填写收礼人的称呼').css("display","inline-block");
		}else if(reg.test(value)){
			$(this).addClass("on").siblings(".conPro01").html('收礼人含有非法字符').css("display","inline-block");
		}
	});
	$(".orderGift .contentBox .giftName02").bind("blur",function(){
		var reg=/[;\/<>\*"'\.~=\+\^%\$@&{}\\]+/g;
		var value = $.trim($(this).val());
		if(value==""){
			$(this).addClass("on").siblings(".conPro01").html('请填写送礼人').css("display","inline-block");
		}else if(reg.test(value)){
			$(this).addClass("on").siblings(".conPro01").html('送礼人含有非法字符').css("display","inline-block");
		}
	});
	$(".orderGift .contentBox textarea").bind("blur",function(){
		var reg=/[;\/<>\*"'\.~=\+\^%\$@&{}\\]+/g;
		var value = $.trim($(this).val());
		if(value==""){
		}else if(reg.test(value)){
			$(this).addClass("on").siblings(".conPro01").html('留言含有非法字符').css("display","inline-block");
		}
	});
	$(".orderGift .contentBox input,.orderGift .contentBox textarea").bind("focus",function(){
		$(this).removeClass("on").siblings(".conPro01").hide();
	});
	$(".orderGift .conSubmit").bind("click",function(){
		var reg=/[;\/<>\*"'\.~=\+\^%\$@&{}\\]+/g;
		var giftName01 = $.trim($(".orderGift .giftName01").val());
		if($.trim(giftName01)==""){
			$(".orderGift .contentBox .giftName01").addClass("on").siblings(".conPro01").html('请填写收礼人的称呼').css("display","inline-block");
			return false;
		}else if(reg.test(giftName01)){
			$(".orderGift .contentBox .giftName01").addClass("on").siblings(".conPro01").html('收礼人含有非法字符').css("display","inline-block");
			return false;
		}
		var giftName02 = $.trim($(".orderGift .giftName02").val());
		if($.trim(giftName02)==""){
			$(".orderGift .contentBox .giftName02").addClass("on").siblings(".conPro01").html('请填写送礼人').css("display","inline-block");
			return false;
		}else if(reg.test(giftName02)){
			$(".orderGift .contentBox .giftName02").addClass("on").siblings(".conPro01").html('送礼人含有非法字符').css("display","inline-block");
			return false;
		}
		var giftPhone = $.trim($(".orderGift .giftPhone").val());
		reg = /^1[3|4|5|7|8][0-9]{9}$/;
		if(giftPhone==""||!reg.test(giftPhone)){
			$(".orderGift .contentBox .giftPhone").addClass("on").siblings(".conPro01").css("display","inline-block");
			return false;
		}
		reg=/[;\/<>\*"'\.~=\+\^%\$@&{}\\]+/g;
		var note = $.trim($("#give_gift_note").val());
		if(note!=""&&reg.test(note)){
			$(".orderGift .contentBox textarea").addClass("on").siblings(".conPro01").css("display","inline-block");
			return false;
		}
		$(".orderGift .contentInfo .giftName01").text(giftName01);
		$(".orderGift .contentInfo .giftName02").text(giftName02);
		$(".orderGift .contentInfo .giftPhone").text(giftPhone);
		$(".orderGift .contentBox,.submit-pro").hide();
		$(".orderGift .contentInfo,.orderGift .modifyPayment").show();
		$(".orderInvoice").hide();
	});
	/*礼品订单end*/
	
	//结算层固定定位
	$(window).bind('scroll',function(){
		divTop=$(window).scrollTop()+$(window).height()-62;
		if(divTop<scrollTop){
			$("#orderTotal").addClass("orderTotalFixed").removeClass("orderTotal");

		}else{
		  	$("#orderTotal").removeClass("orderTotalFixed").addClass("orderTotal");
		}
	});
	/*结算信息end*/
	//取消下单
	$(".pop-wrap .alertCancel, .pop-wrap .alertClose").click(function(){
		$(".pop-wrap,.pop-modal").hide();		
	});
	
	$(":radio[name='InvoiceCustom']").live("click",function(e) {
		if($(this).val()==1){
			$("#inv_title").removeClass("on").hide();
			$(".itemsWrap .contentBox .conPro01").hide();
		}else{
			$("#inv_title").show();
		}
		e.stopPropagation();
    });
	//继续下单
	$(".pop-wrap .alertSure").click(function(){
		$(".pop-wrap,.pop-modal").hide();	
		setCookie("knowStopDelivery","true",1);
	});
 })
function bindAddressClick(){
	//选择地址
	$(".orderAddress .addressList .item").bind("click",function(e) {
		$(".orderAddress .addressList .item").removeClass("on");
        $(this).addClass("on");
        var inv_type = $("input[name=inv_type]:checked").val();
        if($(this).attr("einv")=="true"){
        	//此地址支持电子发票
        	choseInvoiceType(0);
        	//showInvoiceType(1);
	 		//$(".orderInvoice .contentInfo .invoiceKinds").text("电子发票");
        	//if(hasViewedInvo){$(".orderInvoice .contentBox").show();}
        }else{
        	//此地址不支持电子发票
        	choseInvoiceType(1);
        	showInvoiceType(2);
	 		$(".orderInvoice .contentInfo .invoiceKinds").text("纸质发票");
	 		if(hasViewedInvo&&inv_type==1)
	 			$(".orderInvoice .contentBox").show();
        }
		$(".submit-pro").hide();
		removeDisabledButton();
		e.stopPropagation();
		refreshGoodsList(false,$(this).find('input').attr("addressname"));
		var text = $(".orderAddress .addressOpen").find("b").text();
		if(text=="收起"){
			$(".orderAddress .addressOpen").click();
		}
		isSupportAliBillPay();
    });
	
	//设置默认地址
	$(".defaultBtn").bind("click",function(e) {
		$(".orderAddress .addressList .defaultBtn").removeAttr("style");
		$(".orderAddress .addressList .item .addDefault").removeClass("defOn");
		$(this).next().addClass("defOn").show();
		$(this).hide();
		e.stopPropagation();
		var addressId= $(this).attr("_di");
		jQuery.ajax({
			 type:'post',
			 url:'/order/updateUserDefAddress.htm',
			 data:{addressId:addressId},
			 dataType:'json',
			 cache:false,
			 async:true,
			 success:function(data){
				 if(data.state=="fail"){
					 alert("操作失败,请稍后重试!!!");
					 return false;
				 }
				 $("#defAddressID").val(addressId);
			 },
			 error:function(){
				 alert("操作失败,请稍后重试!!!");
				 return false;
			 }
		});
    });
	$(".orderAddress .addNewAdd,.addressList .add").bind("click",function(e) {
		loadAddress(0);	//默认北京市
		$(".addresPopBox .addPopTit strong").html('新增地址');
		$(".addPopCon input").val('');
		$(".addresPopBox,.popMask").show();	
    });
	//删除
	$(".addDelete").bind("click",function(e){
		var _this = $(this);
		$.showAlert({"title":"删除商品","content":"确认要删除？", "type":"confirm","cancelShow":true,
			callback:function() {
				delUserAddress(_this.attr('_di'));
		}});
		e.stopPropagation();
	})
    //修改
	$(".addAlter").bind("click",function(e){
		addressSubmitStatus1=true; //地址能否提交状态	
		addressSubmitStatus3=true; //地址能否提交状态	
		addressSubmitStatus4=true; //地址能否提交状态
		loadAddress(0);	//默认北京市
		$(".addresPopBox .addPopTit strong").html('修改地址');
		$(".addresPopBox,.popMask input").val("");
		$(".addresPopBox,.popMask input").attr("a","1"); 
		$(".popMask input").css("background","#fff");
		
		jQuery.ajax({
			 type:'post',
			 url:'/order/getUserAddressDetail.htm',
			 data:{'id':$(this).attr('_di')},
			 dataType:'json',
			 cache:false,
			 async:false,
			 success:function(data){
				 if(data != null && data.usr_UserAdress != null){
					$("#ID").val(data.usr_UserAdress.ID);
					$("#new_username").val(data.usr_UserAdress.consignee);
					$("#new_detail").val(data.usr_UserAdress.addressMore);
					$("#new_postcode").val(data.usr_UserAdress.zipcode);
					$("#new_phone").val(data.usr_UserAdress.mobile);
					$("#new_tele").val(data.usr_UserAdress.phone);
					loadAddress(data.usr_UserAdress.rgn_RegionID);
					$("#new_username").focus();
			        $(".addresPopBox,.popMask").show();	
			 	}
			 },
			 error:function(){
				 alert("操作失败,请稍后重试!!!");
			 }
		 });
		e.stopPropagation();
	  })
	
}
//从用户选择的地址判断该区域是否支持支付宝货到付款
function isSupportAliBillPay(){
	var regionId = $(".addressList .on input").attr("regionid");
	jQuery.ajax({
		type:'post',
		url:'/order/isSupportAliBillPay.htm',
		data:{'regionId':regionId},
		dataType:'json',
		cahce:false,
		async:false,
		success:function(data){
			if(data.status == 1){//用户所选区域支付宝扫码支付
				//var isSpitOrder = $("#isDiffentCompartment").val();
				//if(isSpitOrder == 0){
					$("#aliBill").show();
			//	}
				
			}else if(data.status == 0){
				$("#aliBill").hide();
				if($("#aliBillPay").attr('checked') == 'checked'){
					$("#huodaofukuan").attr('checked','checked');
				}
				$("#aliBillPay").removeAttr("checked");
				/*if($("#huodaofukuan").attr('checked') == 'checked'){
					$("#huodaofukuan").attr('checked','checked');
				}
				if($("#zhifu").attr('checked') == 'checked'){
					$("#zhifu").attr('checked','checked');
				}*/
				
			}
		}
		
	});
}